import axios from 'axios'
// import { ElMessage } from 'element-plus'
import {useUserStore} from "@store/userStore.js";
// import { useUserStore } from '@/store/user'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
    const userStore = useUserStore()
    if (userStore.token) {
        config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
})

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 处理二进制响应（如图片请求）
        if (response.config.responseType === 'blob') {
            return response
        }

        // 根据后端ApiResult结构处理
        if (response.data?.success === false) {
            ElMessage.error(response.data.message)
            return Promise.reject(response.data)
        }
        return response.data
    },
    async error => {
        const userStore = useUserStore()
        const status = error.response?.status
        console.log(error)
        // 处理401未授权
        if (status === 401) {
            await userStore.logout()
            window.location.reload() // 强制刷新清空状态
            ElMessage.error('登录已过期，请重新登录')
        }
        ElMessage.error(error.response?.data?.message || status)
        return Promise.reject(error)
    }
)

export default service